package org.gd.helloconcurrent.simple;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;

public class SimpleCallable implements Callable<Integer> {

    private AtomicInteger count = new AtomicInteger(0);
    private Future<Integer> dependency;

    public SimpleCallable() {
    }

    public SimpleCallable(Future<Integer> dependency) {
        this.dependency = dependency;
    }

    @Override
    public Integer call() throws Exception {
        if(dependency != null) {
            for(;;) {
                if(dependency.isDone()) {
                    System.out.println("dependency is done");
                    break;
                }
            }
        }
        if(dependency == null) {
            System.out.println("dependency start");
            Thread.sleep(2000L);
        }
        System.out.printf("%s: %s\n",
                Thread.currentThread().getName(),
                String.valueOf(count.incrementAndGet()));
        if(dependency == null) {
            System.out.println("dependency stop");
        }
        return count.get();
    }
}
